import React, { useState } from 'react';
import styles from './index.less';
import { Drawer, Modal, Spin, Table } from 'antd';
import { connect } from 'umi';
import { operateLogType } from '../../constant';
import { downShow, operateLog, operateLogModal, selectedCircle, upHide } from '@/assets';
import planIcon from '@/assets/img/plan_icon.png';
import { log_detail } from '../../../../../assets';
import { queryOperateLog } from '../..//services';
import { HttpCode } from '#/utils/contacts';
import { buildDataKey, tableStyle } from '@/pages/Tianji/InterprovincialSpotDeclaration/helper';
import { TjTable } from '@/pages/ETrade/components';
import { features, useTablePipeline } from 'ali-react-table';
import _ from 'lodash';
import { FileTextOutlined, UpSquareOutlined, DownSquareOutlined } from '@ant-design/icons';

const { Column } = Table;
const OperateLogModal = ({ powerLimitInfo, provinceId, date, type }) => {
  const [logList, setLogList] = useState([]),
    [showLog, setShowLog] = useState(false),
    [loading, setLoading] = useState(false),
    [showModal, setShowModal] = useState(false),
    [detail_info, setDetail_info] = useState({});

  const fetch = async () => {
    setLoading(true);
    let startDate = '';
    let endDate = '';
    startDate = date?.split(',')?.[0] || '';
    endDate = date?.split(',')?.[1] || '';
    const res = await queryOperateLog({
      provinceId,
      dayType: type,
      startDate,
      endDate,
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      let list = res.data.map((item) => {
        return { ...item, showDetail: item.list.length < 2 };
      });
      setLogList(list);
    }
    setLoading(false);
  };
  const changeShowDetail = (index) => {
    let data = JSON.parse(JSON.stringify(logList));
    data[index].showDetail = !data[index].showDetail;
    setLogList(data);
  };

  const columns = [
    {
      code: 'stationName',
      name: '场站',
      width: 80,
      align: 'center',
      features: { autoRowSpan: true },
    },
    {
      code: 'markDate',
      name: '标的日',
      width: 80,
      align: 'center',
      features: { autoRowSpan: true },
    },
    {
      code: 'strategyName',
      name: '所属方案',
      width: 100,
      align: 'center',
      features: { autoRowSpan: true },
    },
    {
      code: 'hourOrder',
      name: '时间段',
      width: 80,
      align: 'center',
      features: { autoRowSpan: true },
    },
    {
      code: 'step',
      name: '阶梯段',
      width: 80,
      align: 'center',
    },
    {
      code: 'electricEnergy',
      name: (
        <>
          电力<span className={styles.danwei}>（MW）</span>
        </>
      ),
      width: 80,
      align: 'center',
    },
    {
      code: 'electricPrice',
      name: (
        <>
          电价<span className={styles.danwei}>（元/MWh）</span>
        </>
      ),
      width: 80,
      align: 'center',
    },
  ];

  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: detail_info?.detail || [], columns })
    .primaryKey('key')
    .use(features.autoRowSpan());

  return (
    <>
      <Drawer
        className={styles.operateLogModal}
        title={
          <div className={styles.modalTitle}>
            <img src={operateLogModal} />
            <span className={styles.text}>操作日志</span>
          </div>
        }
        width={420}
        footer={null}
        visible={showLog}
        onClose={() => {
          setShowLog(false);
        }}
      >
        <Spin spinning={loading}>
          <div className={styles.content}>
            {logList.map((item, index) => (
              <div className={`${styles.item} ${item.showDetail ? styles.show : ''}`} key={index}>
                <div className={styles.itemHeader}>
                  <div className={styles.left}>
                    {/* {index === 0 ? <img src={selectedCircle} /> : <div className={styles.circle} />} */}
                    <div
                      className={index === 0 ? `${styles.circle} ${styles.isFirst}` : styles.circle}
                    />
                    <span className={styles.dateTime}>{item.date}</span>
                    {/* <img
                      className={styles.arrow}
                      src={item.showDetail ? upHide : downShow}
                      onClick={() => changeShowDetail(index)}
                    /> */}

                    {item.showDetail ? (
                      <UpSquareOutlined
                        // style={{ color: 'var(--bd-primary)', marginLeft: 12 }}
                        className={styles.arrow}
                        onClick={() => changeShowDetail(index)}
                      />
                    ) : (
                      <DownSquareOutlined
                        // style={{ color: 'var(--bd-primary)', marginLeft: 12 }}
                        className={styles.arrow}
                        onClick={() => changeShowDetail(index)}
                      />
                    )}
                  </div>
                </div>
                <div className={styles.itemContent}>
                  {item.list.map((item1, index1) => (
                    <div className={styles.operate_box} key={index1}>
                      <div className={styles.flex_row}>
                        <div className={styles.operate_title}>{item1.title}</div>
                        <div
                          className={styles.operate_detail}
                          onClick={() => {
                            let value = _.cloneDeep(item1);
                            value.detail = buildDataKey(value?.detail || []);
                            setDetail_info(value);
                            setShowModal(true);
                          }}
                        >
                          <img src={log_detail} />
                          详情
                        </div>
                      </div>
                      <div className={styles.flex_row1}>
                        <div>
                          <div className={styles.flex_row}>
                            <div
                              className={styles.operate_label}
                              style={{
                                color: operateLogType[item1.operate]?.color || null,
                                background: operateLogType[item1.operate]?.bg || null,
                              }}
                            >
                              {operateLogType[item1.operate]?.label || ''}
                            </div>
                            <div>{item1.time}</div>
                          </div>
                        </div>
                        <div>
                          <span className={styles.gray}>操作人：</span>
                          {item1.userName}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </Spin>
      </Drawer>
      <Modal
        className={styles.model_detail}
        centered={true}
        title={
          <div className={styles.modalTitle}>
            <img src={planIcon} />
            <span className={styles.text}>操作详情</span>
          </div>
        }
        footer={null}
        visible={showModal}
        onCancel={() => {
          setShowModal(false);
        }}
      >
        <div className={styles.flex_row}>
          <div className={styles.flex_row}>
            <div
              className={styles.operate_label}
              style={{
                color: operateLogType[detail_info.operate]?.color || null,
                background: operateLogType[detail_info.operate]?.bg || null,
              }}
            >
              {operateLogType[detail_info.operate]?.label || ''}
            </div>
            {detail_info.operate == '定时申报' && (
              <div className={styles.right__save_info}>
                <span>定时时间：</span>
                {detail_info?.setTime}
              </div>
            )}
          </div>
          <div className={styles.right__save_info}>
            <span>操作时间：</span>
            {detail_info.time}
            <span>操作人：</span>
            {detail_info.userName}
          </div>
        </div>
        <TjTable
          style={{ ...tableStyle, marginTop: '16px' }}
          useOuterBorder={true}
          stickyScrollHeight={10}
          useVirtual={{ horizontal: true, vertical: true, header: false }}
          defaultColumnWidth={100}
          {...pipeline.getProps()}
        />
      </Modal>
      <div
        className={styles.operateLog}
        onClick={() => {
          setShowLog(true);
          fetch();
        }}
      >
        {/* <img className={styles.icon} src={operateLog} /> */}
        <FileTextOutlined className={styles.icon} />
        <span>操作日志</span>
      </div>
    </>
  );
};

export default connect(({ interprovincialSpotDeclaration }) => ({
  powerLimitInfo: interprovincialSpotDeclaration.powerLimitInfo,
  provinceId: interprovincialSpotDeclaration.provinceId,
  date: interprovincialSpotDeclaration.date,
  type: interprovincialSpotDeclaration.type,
}))(OperateLogModal);
